package com.frejoys.store.controller;

import com.frejoys.common.aop.Authority;
import com.frejoys.common.aop.Authorization;
import com.frejoys.common.aop.VerifyStore;
import com.frejoys.common.constant.CommonConstant;
import com.frejoys.common.dto.admin.SubmitVerifyDto;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.response.Result;
import com.frejoys.common.util.CacheKeyUtil;
import com.frejoys.common.util.RequestUtil;
import com.frejoys.service.AdminVerifyService;
import com.frejoys.service.CommonService;
import com.frejoys.service.StoreService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "通用接口", description = "通用接口")
@RestController
@RequiredArgsConstructor
@RequestMapping(CommonConstant.routePrefixStore)
@Authorization(Authority.Private)
public class MallCommonController {


    private final StoreService storeService;

    private final CommonService commonService;

    private final AdminVerifyService adminVerifyService;

    private final RedissonClient redissonClient;

    @VerifyStore
    @Operation(summary = "提交上架审核(店铺,商品,活动)")
    @PostMapping("/common/submitVerify")
    public Result<String> submitVerify(@RequestBody @Validated SubmitVerifyDto dto) {
        RLock lock = redissonClient.getLock(CacheKeyUtil.soldOutLockCacheKey(RequestUtil.userId()));

        if (lock.tryLock()) {
            try {

                adminVerifyService.submitVerify(dto);

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success();
    }

    @VerifyStore
    @Operation(summary = "下架(店铺,商品,活动)")
    @PostMapping("/common/offShelve")
    public Result<String> offShelve(@RequestBody @Validated SubmitVerifyDto dto) {
        RLock lock = redissonClient.getLock(CacheKeyUtil.soldOutLockCacheKey(RequestUtil.userId()));

        if (lock.tryLock()) {
            try {

                commonService.offShelve(dto);

            } finally {
                if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        } else {
            throw new GeneralException(HttpStatus.beingProcessed);
        }

        return Result.success();
    }



}
